package com.xc.ksxt.controller;

import com.alibaba.fastjson.JSON;
import com.xc.common.object.LayuiTableResponse;
import com.xc.common.object.PageInfo;
import com.xc.common.object.ResponseEntity;
import com.xc.common.tool.Helper;
import com.xc.db.tables.ImportRecord;
import com.xc.db.tables.LibChoice;
import com.xc.db.tables.LibQuestion;
import com.xc.ksxt.entity.*;
import com.xc.ksxt.service.*;
import com.xc.ksxt.vo.ImportRecordVO;
import com.xc.sys.entity.SysDictEntity;
import com.xc.sys.entity.SysUserEntity;
import com.xc.sys.service.BaseCodeNumberService;
import com.xc.sys.service.SysDictService;
import com.xc.sys.service.SysUserService;
import com.xc.sys.vo.SysUserVO;
import org.apache.commons.lang3.StringUtils;
import org.jooq.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/importRecord")
public class ImportRecordController {

    @Autowired
    private DSLContext dsl;
    @Autowired
    private ImportRecordService importRecordService;
    @Autowired
    private LibQuestionService libQuestionService;
    @Autowired
    private LibChoiceService libChoiceService;
    @Autowired
    private ChoiceService choiceService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private PaperService paperService;
    private LibQuestion LIBQUESTIONTB = LibQuestion.LIB_QUESTION.as("LIBQUESTIONTB");
    private LibChoice LIBCHOICETB = LibChoice.LIB_CHOICE.as("LIBCHOICETB");
    private ImportRecord IMPORTRECORD = ImportRecord.IMPORT_RECORD.as("IMPORTRECORD");

    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
    @RequestMapping({"/getPageList"})
    public LayuiTableResponse<ImportRecordVO> getPageList(HttpServletRequest request) {
        LayuiTableResponse<ImportRecordVO> ltr = new LayuiTableResponse<>();
        Condition cond = IMPORTRECORD.ID.notEqual(-1);
        String libId = request.getParameter("libId");
        String categoryId = request.getParameter("categoryId");
        Integer limit = Integer.valueOf(request.getParameter("limit"));
        Integer page = Integer.valueOf(request.getParameter("page"));
        if (StringUtils.isNotBlank(libId)) {
            cond = cond.and(IMPORTRECORD.LIB_ID.eq(Integer.valueOf(libId)));
        }
        if (StringUtils.isNotBlank(categoryId)) {
            cond = cond.and(IMPORTRECORD.CATEGORY_ID.eq(Long.valueOf(categoryId)));
        }
        Long count = importRecordService.count(cond);
        ltr.setCount(count);
        PageInfo<ImportRecordEntity> pageInfo = new PageInfo<>(limit, page);
        Result<Record> list = importRecordService.select(cond, pageInfo,IMPORTRECORD.CREATE_TIME.desc());
        List<ImportRecordVO> importRecordEntityList = list.into(ImportRecordVO.class);
        for (ImportRecordVO importRecordEntity : importRecordEntityList){
            setTxt(importRecordEntity);
        }
        ltr.setData(importRecordEntityList);
        return ltr;
    }

    private void setTxt(ImportRecordVO importRecordEntity) {
        SysUserVO user = SysUserService.getFrameCaches(importRecordEntity.getCreateUserId());
        importRecordEntity.setCreateUserName(user==null?"":user.getName());
        LibCategoryEntity category = LibCategoryService.getFromCaches(importRecordEntity.getCategoryId());
        importRecordEntity.setCategoryName(category==null?"":category.getName());
        if(importRecordEntity.getCollegeId()!=null){
            CollegeEntity college = CollegeService.getFromCaches(importRecordEntity.getCollegeId());
            importRecordEntity.setCollegeName(college==null?"":college.getName());
        }
        if(importRecordEntity.getGradeYear()!=null){
            GradeYearEntity gradeYearEntity = GradeYearService.getFromCaches(importRecordEntity.getGradeYear());
            importRecordEntity.setGradeYearName(gradeYearEntity==null?"":gradeYearEntity.getName());
        }
        if(importRecordEntity.getGrade()!=null){
            GradeEntity gradeEntity = GradeService.getFromCaches(importRecordEntity.getGrade());
            importRecordEntity.setGradeName(gradeEntity==null?"":gradeEntity.getName());
        }

        Integer state = importRecordEntity.getState();
        if(state!=null){
            importRecordEntity.setStateTxt(state==1?"待确认":"已确认");
        }
        if(importRecordEntity.getMajorId()!=null){
            MajorEntity majorEntity = MajorService.getFromCaches(importRecordEntity.getMajorId());
            importRecordEntity.setMajorName(majorEntity==null?"":majorEntity.getName());
        }
        if(importRecordEntity.getStudentType()!=null){
            SysDictEntity dict = SysDictService.getFromCaches("student-type," + importRecordEntity.getStudentType());
            importRecordEntity.setStudentTypeTxt(dict==null?null:dict.getName());
        }
        if(importRecordEntity.getSemester()!=null){
            SysDictEntity dict = SysDictService.getFromCaches("semester," + importRecordEntity.getSemester());
            importRecordEntity.setSemesterTxt(dict==null?null:dict.getName());
        }
        if(importRecordEntity.getPaperType()!=null){
            SysDictEntity dict = SysDictService.getFromCaches("paper-type," + importRecordEntity.getPaperType());
            importRecordEntity.setPaperTypeTxt(dict==null?null:dict.getName());
        }
        if(importRecordEntity.getTestPhase()!=null){
            SysDictEntity dict = SysDictService.getFromCaches("test-phase," + importRecordEntity.getTestPhase());
            importRecordEntity.setTestPhaseTxt(dict==null?null:dict.getName());
        }
        if(importRecordEntity.getTestType()!=null){
            SysDictEntity dict = SysDictService.getFromCaches("test-type," + importRecordEntity.getTestType());
            importRecordEntity.setTestTypeTxt(dict==null?null:dict.getName());
        }
        if(importRecordEntity.getLg()!=null){
            SysDictEntity dict = SysDictService.getFromCaches("paper-lg," + importRecordEntity.getLg());
            importRecordEntity.setLgTxt(dict==null?null:dict.getName());
        }
    }

    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
    @RequestMapping({"/getById"})
    public ImportRecordVO getById(Integer id) {
        Record r = importRecordService.getRecordById(id);
        ImportRecordVO v = r.into(ImportRecordVO.class);
        setTxt(v);
        return v;
    }
    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.POST})
    @RequestMapping({"/save"})
    public ResponseEntity<ImportRecordEntity> save(@RequestBody HashMap<String,String> params, HttpServletRequest request) {
        ResponseEntity<ImportRecordEntity> res = new ResponseEntity<>();
        ImportRecordEntity importRecordEntity = Helper.map2Bean(new ImportRecordEntity(), params);

        importRecordService.save(importRecordEntity);
        return res;
    }
    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.POST})
    @RequestMapping({"/delete"})
    public LayuiTableResponse<ImportRecordEntity> delete(@RequestBody Map<String,String> params) {
        String idstr = params.get("ids");
        Integer[] idarr = Helper.str2integerArr(idstr);
        LayuiTableResponse<ImportRecordEntity> ltr = new LayuiTableResponse<>();
        for (Integer id : idarr) {
            ImportRecordEntity m = importRecordService.getEntityById(id);
            if(m.getState()==null||m.getState()==1){
                dsl.delete(LIBQUESTIONTB).where(LIBQUESTIONTB.RECORD_ID.eq(id)).execute();
                dsl.delete(LIBCHOICETB).where(LIBCHOICETB.RECORD_ID.eq(id)).execute();
                dsl.delete(IMPORTRECORD).where(IMPORTRECORD.ID.eq(id)).execute();
            }
        }
        return ltr;
    }
    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.POST})
    @RequestMapping({"/confirm"})
    public LayuiTableResponse<ImportRecordEntity> confirm(@RequestBody Map<String,String> params,HttpServletRequest request) {
        SysUserEntity me = Helper.getMe(request);
        String idstr = params.get("ids");
        Integer[] idarr = Helper.str2integerArr(idstr);
        LayuiTableResponse<ImportRecordEntity> ltr = new LayuiTableResponse<>();
        for (Integer id : idarr) {
            ImportRecordEntity m = importRecordService.getEntityById(id);
            if(m.getState()==null||m.getState()==1){
                dsl.fetch("update paper set state=2 where import_id=?",id);
                dsl.fetch("update lib_question set del_flag=1 where record_id=?",id);
                dsl.fetch("update lib_choice set del_flag=1 where record_id=?",id);
                m.setState(2);
                importRecordService.update(m);
                PaperEntity paperEntity = newPaper(m,me);
                List<LibQuestionEntity> libqs = libQuestionService.select(LIBQUESTIONTB.RECORD_ID.eq(id));
                for (LibQuestionEntity libq : libqs) {
                    QuestionEntity qe = insertQuestion(paperEntity, libq);
                    List<LibChoiceEntity> libcs = libChoiceService.select(LIBCHOICETB.LIB_QUESTION_ID.eq(Long.valueOf(libq.getId())).and(LIBCHOICETB.DEL_FLAG.notEqual(-1)));
                    for (LibChoiceEntity libc : libcs) {
                        insertChoice(paperEntity,libq,qe,libc);
                    }
                }

            }
        }

        return ltr;
    }
    private PaperEntity newPaper(ImportRecordEntity ire, SysUserEntity me){
        PaperEntity paperEntity = new PaperEntity();
        String paperId = Helper.getSnowId() + "";
        paperEntity.setId(paperId);
        SysDictEntity dict = SysDictService.getFromCaches("student-type,"+ire.getStudentType());
        SysDictEntity dict2 = SysDictService.getFromCaches("test-phase,"+ire.getTestPhase());
        String name = "中山大学" + dict.getName() + dict2.getName() + "考试";
        paperEntity.setName(name);

        paperEntity.setTestPhase(ire.getTestPhase()==null?null:ire.getTestPhase());
        paperEntity.setPaperType(ire.getPaperType()==null?null:ire.getPaperType());
        paperEntity.setStudentType(ire.getStudentType()==null?null:ire.getStudentType());
        paperEntity.setCreateTime(LocalDateTime.now());
        paperEntity.setCreateUserId(me.getId());
        paperEntity.setMajor(ire.getMajorId());
        paperEntity.setLg(ire.getLg()==null?null:ire.getLg());
        paperEntity.setCategoryId(ire.getCategoryId());
        paperEntity.setCollegeId(ire.getCollegeId());
        paperEntity.setHowlong(ire.getHowlong()==null?null:ire.getHowlong());
        paperEntity.setGradeYear(ire.getGradeYear());
        paperEntity.setGrade(ire.getGrade());
        paperEntity.setState(2);
        paperEntity.setImportId(ire.getId());
        if(ire.getSemester()!=null){
            paperEntity.setSemester(ire.getSemester());
        }
        if(ire.getTestType()!=null){
            paperEntity.setTestType(ire.getTestType());
        }
        String code = BaseCodeNumberService.genCode("paper-code", 4);
        paperEntity.setCode(code);
        paperService.save(paperEntity);
        return paperEntity;
    }
    private QuestionEntity insertQuestion(PaperEntity paperEntity,LibQuestionEntity lqe){
        QuestionEntity qe = new QuestionEntity();
        qe.setLg(lqe.getLg());
        qe.setDifficulty(lqe.getDifficulty());
        qe.setLibId(lqe.getLibId());
        qe.setOrderno(lqe.getOrderno());
        qe.setAnalysis(lqe.getAnalysis());
        qe.setCategoryId(lqe.getCategoryId());
        qe.setPianId(lqe.getPianId());
        qe.setJieId(lqe.getJieId());
        qe.setChapterId(lqe.getChapterId());
        qe.setContentType(lqe.getContentType());
        qe.setSource(lqe.getSource());
        qe.setCreateTime(LocalDateTime.now());
        qe.setText(lqe.getText());
        qe.setAnswerText(lqe.getAnswerText());
        qe.setQuestionType(lqe.getQuestionType());
        qe.setCreateUserId(lqe.getCreateUserId());
        qe.setLibQuestionId(lqe.getId());
        qe.setPaperId(paperEntity.getId());
        questionService.insert(qe);
        return qe;
    }
    private void insertChoice(PaperEntity paperEntity,LibQuestionEntity lqe,QuestionEntity qe,LibChoiceEntity lce){
        ChoiceEntity ce = new ChoiceEntity();
        ce.setText(lce.getText());
        ce.setLibId(lce.getLibId());
        ce.setLibChoiceId(lce.getId());
        ce.setLibQuestionId(lqe.getId());
        ce.setCreateTime(LocalDateTime.now());
        ce.setRight(lce.getRight());
        ce.setAnswerText(lce.getAnswerText());
        ce.setIndexLetter(lce.getIndexLetter());
        ce.setQuestionId(qe.getId());
        ce.setPaperId(paperEntity.getId());
        choiceService.insert(ce);
    }
}
